package org.eoti.elec;

/**
 * The MIT License
 * <p/>
 * Copyright (c) 2009 Malachi de AElfweald (malachid@gmail.com)
 * <p/>
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * <p/>
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * <p/>
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

import org.eoti.spec.raijin.v1.WireConfig;
import org.eoti.spec.raijin.v1.WireEndpoint;

import java.util.concurrent.CopyOnWriteArrayList;

public class Wire
implements TickListener
{
	protected Pin in;
	protected CopyOnWriteArrayList<Pin> out = new CopyOnWriteArrayList<Pin>();

	public Wire(DigitalCircuit source, WireConfig config)
	{
		WireEndpoint from = config.getFrom();
		DigitalComponent compFrom = source;
		if(from.isSetComponent())
			compFrom = source.getComponent(from.getComponent());

		in = compFrom.getBufferedPin(from.getPin());
		if(in == null)
			in = compFrom.getPin(from.getPin());

//		if(in.getType() != Pin.Type.Output) throw new IllegalArgumentException("Only output pins can provide input to the wire.");

		for( WireEndpoint to : config.getTo())
		{
			DigitalComponent compTo = source;
			if(to.isSetComponent())
				compTo = source.getComponent(to.getComponent());

			Pin pinTo = compTo.getBufferedPin(to.getPin());
			if(pinTo == null)
				pinTo = compTo.getPin(to.getPin());

//			if(pinTo.getType() != Pin.Type.Input) throw new IllegalArgumentException("Only input pins can recieve output from a wire.");
			out.add(pinTo);
		}

//		TickGenerator.getInstance().addTickListener(this);
	}

	public Wire(Pin in, Pin ... out)
	{
//		if(in.getType() != Pin.Type.Output) throw new IllegalArgumentException("Only output pins can provide input to the wire.");

		for(Pin pOut : out)
		{
//			if(pOut.getType() != Pin.Type.Input) throw new IllegalArgumentException("Only input pins can recieve output from a wire.");
			this.out.add(pOut);
		}

		this.in = in;

//		TickGenerator.getInstance().addTickListener(this);
	}

	public void tick()
	{
		for(Pin pin : out)
			pin.setState(in.getState());
	}
}
